/// 睡眠阶段枚举
enum SleepStage {
  deep(1, 'Deep', '深睡'),
  light(2, 'Light', '浅睡'),
  rem(3, 'REM', '眼动期'),
  awake(4, 'Awake', '清醒');

  const SleepStage(this.value, this.nameEn, this.nameCn);

  final int value;
  final String nameEn;
  final String nameCn;

  /// 获取本地化名称
  String getLocalizedName(bool useChinese) {
    return useChinese ? '$nameEn $nameCn' : nameEn;
  }

  /// 从值获取睡眠阶段
  static SleepStage? fromValue(int value) {
    for (final stage in SleepStage.values) {
      if (stage.value == value) return stage;
    }
    return null;
  }
}

/// 单个睡眠数据点
class SleepDataPoint {
  final SleepStage stage;
  final int durationMinutes;

  const SleepDataPoint({
    required this.stage,
    required this.durationMinutes,
  });

  /// 从列表创建数据点
  factory SleepDataPoint.fromList(List<int> data) {
    if (data.length != 2) {
      throw ArgumentError('Data must contain exactly 2 elements: [stage, duration]');
    }
    
    final stage = SleepStage.fromValue(data[0]);
    if (stage == null) {
      throw ArgumentError('Invalid sleep stage value: ${data[0]}');
    }
    
    if (data[1] < 0) {
      throw ArgumentError('Duration must be non-negative: ${data[1]}');
    }

    return SleepDataPoint(
      stage: stage,
      durationMinutes: data[1],
    );
  }

  /// 转换为列表格式
  List<int> toList() => [stage.value, durationMinutes];

  @override
  String toString() => 'SleepDataPoint(${stage.nameEn}: ${durationMinutes}min)';
}

/// 睡眠统计数据
class SleepStats {
  final Map<SleepStage, int> stageDurations;
  final int totalSleepMinutes;
  final int totalBedTimeMinutes;

  const SleepStats({
    required this.stageDurations,
    required this.totalSleepMinutes,
    required this.totalBedTimeMinutes,
  });

  /// 从睡眠数据计算统计
  factory SleepStats.fromData(List<SleepDataPoint> data, {int additionalBedTimeMinutes = 45}) {
    final Map<SleepStage, int> stageDurations = {};
    
    // 初始化所有阶段为0
    for (final stage in SleepStage.values) {
      stageDurations[stage] = 0;
    }
    
    // 计算各阶段时长
    for (final point in data) {
      stageDurations[point.stage] = (stageDurations[point.stage] ?? 0) + point.durationMinutes;
    }
    
    final totalSleep = stageDurations.values.reduce((a, b) => a + b);
    
    return SleepStats(
      stageDurations: stageDurations,
      totalSleepMinutes: totalSleep,
      totalBedTimeMinutes: totalSleep + additionalBedTimeMinutes,
    );
  }

  /// 获取指定阶段的时长
  int getDuration(SleepStage stage) => stageDurations[stage] ?? 0;

  /// 格式化时长为小时分钟
  String formatDuration(int minutes) {
    if (minutes < 60) return '${minutes}m';
    final hours = minutes ~/ 60;
    final mins = minutes % 60;
    return mins > 0 ? '${hours}h ${mins}m' : '${hours}h';
  }

  /// 格式化总睡眠时长
  String get formattedTotalSleep => formatDuration(totalSleepMinutes);

  /// 格式化总卧床时长
  String get formattedTotalBedTime => formatDuration(totalBedTimeMinutes);
} 